<?php

namespace app\user\controller\iot\reservation;

use app\admin\service\UserService;
use app\BaseController;
use app\model\iot_model\IotRoom;
use app\model\iot_model\IotRoomReservation;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 功能室
     * @return bool|string
     */
    public function room(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $IotRoomModel = new IotRoom();
            $data = $IotRoomModel->where($where)->with(['iotFunctionRoom'])->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 当天可预约时段
     * @return bool|string
     */
    public function dateView(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'date|日期' => 'require'
            ]);
            $IotRoomModel = new IotRoom();
            $info = $IotRoomModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $week = explode(',',$info['week']);
            $num = date('N', strtotime($param['date']));
            if (!in_array($num,$week)) throw new \Exception('周'.$num.'未开放，请预约其他时间！');
            $IotRoomReservationModel = new IotRoomReservation();
            $timeList = $IotRoomReservationModel->field('id,uid,start_time')->where([
                ['room_id','=',$param['id']],
                ['reserve_date','=',date('Ymd',strtotime($param['date']))]
            ])->select()->toArray();
            $timeData = [];
            foreach ($timeList as $v) {
                $timeData[date('H:i',$v['start_time'])][$v['uid']] = $v;
            }
            $data = [];
            //上午
            if ($info['morning_open'] == 1){
               $time = $info['morning_end'] - $info['morning_start'];
               $num = intval($time/60/$info['morning_interval']);
               for ($i = 1; $i <= $num; $i++){
                   $status = 0;
                   $hi = date('H:i',$info['morning_start']+($i*$info['morning_interval']*60));
                   if (!empty($timeData[$hi])){
                       if (!empty($timeData[$hi][$this->userData['id']])){
                           $status = 1;
                       }else{
                           if (count($timeData[$hi]) >= $info['per_slot_people']){
                               $status = 2;
                           }
                       }
                   }
                   $data[] = [
                       'date' => $hi,
                       'status' => $status
                   ];
               }
            }
            //下午
            if ($info['afternoon_open'] == 1){
                $time = $info['afternoon_end'] - $info['afternoon_start'];
                $num = intval($time/60/$info['afternoon_interval']);
                for ($i = 1; $i <= $num; $i++){
                    $status = 0;
                    $hi = date('H:i',$info['afternoon_start']+($i*$info['afternoon_interval']*60));
                    if (!empty($timeData[$hi])){
                        if (!empty($timeData[$hi][$this->userData['id']])){
                            $status = 1;
                        }else{
                            if (count($timeData[$hi]) >= $info['per_slot_people']){
                                $status = 2;
                            }
                        }
                    }
                    $data[] = [
                        'date' => $hi,
                        'status' => $status
                    ];
                }
            }
            //晚上
            if ($info['evening_open'] == 1){
                $time = $info['evening_end'] - $info['evening_start'];
                $num = intval($time/60/$info['evening_interval']);
                for ($i = 1; $i <= $num; $i++){
                    $status = 0;
                    $hi = date('H:i',$info['evening_start']+($i*$info['evening_interval']*60));
                    if (!empty($timeData[$hi])){
                        if (!empty($timeData[$hi][$this->userData['id']])){
                            $status = 1;
                        }else{
                            if (count($timeData[$hi]) >= $info['per_slot_people']){
                                $status = 2;
                            }
                        }
                    }
                    $data[] = [
                        'date' => $hi,
                        'status' => $status
                    ];
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 提交预约
     * @return bool|string
     */
    public function submit(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'date|时间' => 'require',
                'hi|时分' => 'require',
            ]);
            $IotRoomModel = new IotRoom();
            $info = $IotRoomModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $week = explode(',',$info['week']);
            $num = date('N', strtotime($param['date']));
            if (!in_array($num,$week)) throw new \Exception('周'.$num.'未开放，请预约其他时间！');
            $IotRoomReservationModel = new IotRoomReservation();
            $timeList = $IotRoomReservationModel->field('id,uid,start_time')->where([
                ['room_id','=',$param['id']],
                ['reserve_date','=',date('Ymd',strtotime($param['date']))]
            ])->select()->toArray();
            $timeData = [];
            foreach ($timeList as $v) {
                $timeData[date('H:i',$v['start_time'])][$v['uid']] = $v;
            }
            if (!empty($timeData[$param['hi']])){
                if (!empty($timeData[$param['hi']][$this->userData['id']])){
                    throw new \Exception('不可重复预约！');
                }elseif (count($timeData[$param['hi']]) >= $info['per_slot_people']){
                    throw new \Exception('当前时段预约人数已满！');
                }
            }
            $date = date('Y-m-d '.$param['hi'].':s');
            $h = date('H',strtotime($date));
            if ($h <= 12){
                $time_slot = 1;
                $start_time = strtotime(date('Y-m-d '.$param['hi'].':s'));
                $end_time = $start_time + ($info['morning_interval'] * 60);
            }elseif ($h <= 18){
                $time_slot = 2;
                $start_time = strtotime(date('Y-m-d '.$param['hi'].':s'));
                $end_time = $start_time + ($info['afternoon_interval'] * 60);
            }elseif ($h <= 23){
                $time_slot = 3;
                $start_time = strtotime(date('Y-m-d '.$param['hi'].':s'));
                $end_time = $start_time + ($info['evening_interval'] * 60);
            }else{
                throw new \Exception('时间参数有误！');
            }
            $IotRoomReservationModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'room_id' => $param['id'],
                'reserve_date' => date('Ymd',strtotime($param['date'])),
                'time_slot' => $time_slot,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'time' => time()
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预约记录
     * @return bool|string
     */
    public function log(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require'
            ]);
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['abc']) && strlen($param['abc']) > 0) {
                if ($param['abc'] == 1){
                    $where[] = ['end_time','<',time()];
                }else{
                    $where[] = ['end_time','>=',time()];
                }
            }
            if (!empty($param['name'])){
                $IotRoomModel = new IotRoom();
                $room_id = $IotRoomModel->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name','like','%'.$param['name'].'%']
                ])->column('id');
                if (!empty($room_id)){
                    $where[] = ['room_id','in',$room_id];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $IotRoomReservationModel = new IotRoomReservation();
            $query = $IotRoomReservationModel->where($where);
            $data = $query->with([
                'room' => function ($query) {
                    $query->with([
                        'iotFunctionRoom'
                    ]);
                }
            ])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 记录详情
     * @return bool|string
     */
    public function logInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $IotRoomReservationModel = new IotRoomReservation();
            $info = $IotRoomReservationModel->with([
                'user',
                'room' => function ($query) {
                    $query->with(['iotFunctionRoom']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $UserService = new UserService($this->app);
            $info['department_name'] = $UserService->getNotDelDepartmentName($this->userData['unit_id'],$info['department_id']);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除记录
     * @return bool|string
     */
    public function deleteLog(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $IotRoomReservationModel = new IotRoomReservation();
            if (is_array($param['id'])) {
                $IotRoomReservationModel->where('id','in',$param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }else{
                $IotRoomReservationModel->where('id','=',$param['id'])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 取消预约
     * @return bool|string
     */
    public function cancel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $IotRoomReservationModel = new IotRoomReservation();
            $info = $IotRoomReservationModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save([
                'status' => 0
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

}